package org.mybatis.plus.boot;

import org.mybatis.plus.core.MapperProxy;
import org.mybatis.plus.core.SqlSessionFactory;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.FactoryBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

/**
 * 自定义的代理工厂，用于将指定的接口转换为代理实体
 */
public class MybatisPlusProxy implements FactoryBean<Object>,ApplicationContextAware {

	private Class<?> interfaceClass;
	private ApplicationContext applicationContext;
	
	public MybatisPlusProxy() {
		super();
	}

	public MybatisPlusProxy(Class<?> interfaceClass) {
		super();
		this.interfaceClass = interfaceClass;
	}

	public Object createBean() {
		return getMapper(interfaceClass,applicationContext.getBean(SqlSessionFactory.class));
	}
	
	public <T> T getMapper(Class<T> c,SqlSessionFactory sqlSessionFactory) {
		MapperProxy<T> mapperProxy = new MapperProxy<T>();
		mapperProxy.setSqlSessionFactory(sqlSessionFactory.build(sqlSessionFactory));
		return (T) mapperProxy.getInstance(c);
	}

	@Override
	public Object getObject() throws Exception {
		return createBean();
	}

	@Override
	public Class<?> getObjectType() {
		return interfaceClass;
	}

	@Override
	public boolean isSingleton() {
		return false;
	}

	@Override
	public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
		 this.applicationContext = applicationContext;
	}

}